package com.basic;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;
/**
 * 功能：转换java源文件的编码格式
 * @author taowei20061122@163.com
 *
 */
public class GBK2UTF8App {

	/**
	 * 将制定目录下的所有Java源文件的编码格式从GBK修改为UTF-8
	 */
	public static void main(String[] args) throws Exception {
		//GBK编码格式源码路径
		String srcDirPath = "E:/generator-output/java_src/";
		//转为UTF-8编码格式源码路径
		String utf8DirPath = "E:/generator-output/java_src/";
		
//		convertUTF_8ToGBK(srcDirPath);
		
		convertGBKToUTF_8(srcDirPath);
	}
	
	/**
	 * 功能：将UTF-8编码的java源文件转换成GBK编码格式
	 * 
	 * @param filePath 文件路径
	 */
	public static void convertUTF_8ToGBK(String filePath) {
		Assert.notNull(filePath, "文件路径不能为空...");
		File file = new File(filePath);
		File[] files = file.listFiles();
		
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				String filePath2 = files[i].getAbsolutePath();
				convertUTF_8ToGBK(filePath2);
			} else {
				String filePath2 = files[i].getAbsolutePath();
				//使用UTF-8读取数据，然后用GBK写入数据
				try {
					FileUtils.writeLines(new File(filePath2),"GBK", FileUtils.readLines(files[i],"UTF-8"));
				} catch (IOException e) {
					e.printStackTrace();
				}		
			}
		}
		System.out.println("Done.");
	}
	/**
	 * 功能：将GBK编码的java源文件转换成UTF-8编码格式
	 * 
	 * @param filePath 文件路径
	 */
	public static void convertGBKToUTF_8(String filePath) {
		Assert.notNull(filePath, "文件路径不能为空...");
		File file = new File(filePath);
		File[] files = file.listFiles();
		
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				String filePath2 = files[i].getAbsolutePath();
				convertUTF_8ToGBK(filePath2);
			} else {
				String filePath2 = files[i].getAbsolutePath();
				//使用GBK读取数据，然后用UTF-8写入数据
				try {
					FileUtils.writeLines(new File(filePath2),"UTF-8", FileUtils.readLines(files[i],"GBK"));
				} catch (IOException e) {
					e.printStackTrace();
				}		
			}
		}
		System.out.println("Done.");
	}
}
